//
//  TopicTableViewController.m
//  NewChat
//
//  Created by lanou3g on 16/2/27.
//  Copyright © 2016年 蓝鸥. All rights reserved.
//

#import "TopicTableViewController.h"
#import "TopicTableViewCell.h"
#import "ClickRightCornerJumpToViewController.h"
#import "MyVoiceViewController.h"
#import "PersonalHomePageTableViewController.h"
#import "ReplyViewController.h"
#import "MHDataHelper.h"
#import "FindModel.h"
#import "SKXRongCloudManager.h"
#import "SKXFriendManager.h"

#define HELPER [MHDataHelper shareDataHelper]
#define PLAY [SKXRongCloudManager sharaManager]

@interface TopicTableViewController ()<MyVoiceViewControllerDelegate>

@property (nonatomic,strong)NSMutableArray *hotChatArray;
@property(nonatomic,strong)UIImageView*backgroundView;
@end

@implementation TopicTableViewController

-(instancetype)initWithStyle:(UITableViewStyle)style{
    
    if(self = [super initWithStyle:UITableViewStyleGrouped]){
        
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
     NSLog(@"这个页面是 社区--> TopicTableViewController");
    //隐藏底部tabbar
    self.tabBarController.tabBar.hidden = YES;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    
        [HELPER requestHotchatArrayWithArrayType:self.aString didFinish:^(NSMutableArray *array) {
            self.hotChatArray = array;
            for (FindModel *find in array) {
                [HELPER getNumbersOfReplyWithOnlyID:find.objectId didFinished:^(NSInteger number) {
                    find.replys = number;
                    [self.tableView reloadData];
                    
                }];
            }
        }];
    });
}


- (void)viewDidLoad {
    [super viewDidLoad];
    

    NSLog(@"这个页面是 社区--> TopicTableViewController");
    //设置右上方按钮
    UIBarButtonItem *BBI1 = [[UIBarButtonItem alloc]initWithTitle:@"🔔" style:(UIBarButtonItemStylePlain) target:self action:@selector(clickRightBarAction1:)];
    
    UIBarButtonItem *BBI2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:(UIBarButtonSystemItemCompose) target:self action:@selector(clickRightBarAction2:)];
    
    
    self.navigationItem.rightBarButtonItems = @[BBI1,BBI2];
    
    self.navigationItem.title = self.aString;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.tableView registerClass:[TopicTableViewCell class] forCellReuseIdentifier:@"TopCell"];
    //添加背景图
    [self addBackgroundPicture];
    //下拉刷新
    self.tableView.mj_header =  [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh)];
}

//添加背景图片
-(void)addBackgroundPicture{
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"2001.jpg"]];
}

-(void)tableViewRefresh{
    RealReachability *reachability = [RealReachability sharedInstance];
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    
    NSLog(@"当前网络状态%ld",status);
    
    if (status == RealStatusNotReachable) {
        
        UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            
            
        }];
        
        UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前无网络连接" preferredStyle:(UIAlertControllerStyleAlert)];
        
        [con addAction:act];
        [self presentViewController:con animated:YES completion:nil];
        
        
    }else{//网络判断
    
    [HELPER requestHotchatArrayWithArrayType:self.aString didFinish:^(NSMutableArray *array) {
        if (self.hotChatArray.count) {
            [self.hotChatArray removeAllObjects];
        }
        self.hotChatArray = array;
        for (FindModel *find in array) {
            [HELPER getNumbersOfReplyWithOnlyID:find.objectId didFinished:^(NSInteger number) {
                find.replys = number;
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"-----%ld",self.hotChatArray.count);
                    [self.tableView reloadData];
                    [self.tableView.mj_header endRefreshing];
                });
                
            }];
        }
    }];
    }//网络判断
}


#pragma mark=========UIBarButtonItem的跳转事件======
-(void)clickRightBarAction1:(UIBarButtonItem*)sender{
    NSLog(@"点击铃铛跳转");
    ClickRightCornerJumpToViewController *clickRightCornerJumpVC = [[ClickRightCornerJumpToViewController alloc]init];
    
    [self showViewController:clickRightCornerJumpVC sender:nil];
}

-(void)clickRightBarAction2:(UIBarButtonItem*)sender{
    NSLog(@"点击编辑跳转");
    MyVoiceViewController *myVoiceVC = [[MyVoiceViewController alloc]init];
    myVoiceVC.MHTopicType = self.aString;
    myVoiceVC.delegate = self;
    myVoiceVC.myVoicetype = @"topic";
    [self showViewController:myVoiceVC sender:nil];
}

-(void)passsValue:(NSString *)string{
    self.aString = string;
    NSLog(@"====%@",self.aString);
    [HELPER requestHotchatArrayWithArrayType:self.aString didFinish:^(NSMutableArray *array) {
        self.hotChatArray = array;
        [self.tableView reloadData];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

//分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    
    return 1;
}

//每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.hotChatArray.count;
}

//区头的高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 1;
}

//cell的高度（自适应）
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    

       return [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
}

//创建cell并赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TopicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TopCell"];

    if (!cell) {
        cell = [[TopicTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"TopCell"];
    }
    
    FindModel *model = self.hotChatArray[self.hotChatArray.count-1-indexPath.row];
    
    cell.userPictureBtn.tag = self.hotChatArray.count-indexPath.row+200;
    [cell.userPictureBtn addTarget:self action:@selector(noticeTopicViewPushNextView:) forControlEvents:(UIControlEventTouchUpInside)];
    // 给cell上的控件赋值
    [cell configureCellWithModel:model];
    
    cell.voiceBtn.tag = indexPath.row +101;
    [cell.voiceBtn addTarget:self action:@selector(topicReplyBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.voiceBtn.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"btncolor.jpg"]];
    
      return cell;
}
-(void)topicReplyBtnAction:(UIButton *)sender{
    FindModel *find = self.hotChatArray[_hotChatArray.count+100-sender.tag];
    [PLAY playRecordSuccessWithURL:find.messageVoice];

    
}

//点击头像的事件
-(void)noticeTopicViewPushNextView:(UIButton*)sender{

    NSLog(@"代理正在执行跳转到PersonalHomePageTableViewController的方法");
    PersonalHomePageTableViewController*perVC = [[PersonalHomePageTableViewController alloc]init];
    //给下个页面传值
    perVC.model = self.hotChatArray[sender.tag-201];
    
    [self.navigationController pushViewController:perVC animated:YES];

}
//cell的点击事件

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"你点击了TopicTableViewController中的cell");
    NSLog(@"即将跳转到的页面是:发现 ——> ReplyViewController");
    
    ReplyViewController*replyVC = [[ReplyViewController alloc]init];
    replyVC.ControlType = @"topic";//给当前控制器加个标记
    
    //给下个页面传值
    replyVC.findModel = self.hotChatArray[self.hotChatArray.count-1-indexPath.row];
    HELPER.pushIndex += 1;
     self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:replyVC animated:YES];
     self.hidesBottomBarWhenPushed = NO;
    
}




/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
-(NSMutableArray *)hotChatArray{
    if (!_hotChatArray) {
        _hotChatArray = [NSMutableArray array];
    }
    return _hotChatArray;
}
@end
